package com.anycc.cloud.common.util;

import com.anycc.cloud.common.dto.query.PagingRequest;
import com.anycc.cloud.common.dto.query.PagingResponse;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;

/**
 * datatables request and response converter
 */
public final class PagingUtil {
    private PagingUtil() {
    }

    public static Pageable buildPageRequest(PagingRequest pagingRequest) {
        if (pagingRequest.getOrders().isEmpty()) {
            return PageRequest.of(pagingRequest.getPage(), pagingRequest.getSize());
        } else {
            List<Sort.Order> orderList = new ArrayList<>();
            pagingRequest.getOrders().forEach(order ->
                    orderList.add(new Sort.Order(Sort.Direction.fromString(order.getDirection()), order.getProperty()))
            );

            return PageRequest.of(pagingRequest.getPage(), pagingRequest.getSize(), Sort.by(orderList));
        }
    }

    public static <T> PagingResponse<T> buildPagingResponse(PagingRequest pagingRequest, Page<T> page) {
        return new PagingResponse<>(pagingRequest, page.getTotalPages(), page.getTotalElements(), page.getContent());
    }
}
